<?php

namespace App\Common\Util\EasySearchMacro;

use App\Common\Interfaces\EasySearchMacroInterface;
use App\Common\Model\Model;
use App\Common\Util\TP;
use think\db\Query;

/**
 * 全局搜索
 */
class GlobalSearch implements EasySearchMacroInterface
{
    /**
     * @param Query|Model $builder
     * @param array<callable<string, Query|Model>> $callable
     * @return void
     */
    public function __invoke(Query|Model $builder, ...$callable): void
    {
        if (!($query = TP::request()->get('query'))
            || (TP::request()->get('search')
                && array_filter(array_column(TP::request()->get('search'), 'search'), fn($v) => $v !== '' && $v !== null))
        ) {
            return;
        }
        parse_str($query, $parse);
        if (empty($parse['global_search'])) return;

        if (current($callable) instanceof \Closure) {
            call_user_func(current($callable), $parse['global_search'], $builder);
        }else{
            $builder->where(function ($builder) use ($parse, $callable){
                foreach ($callable as $field){
                    $builder->whereOr($field, 'like', "%{$parse['global_search']}%");
                }
            });
        }
    }
}